<template>
  <div class="account-transactions">
    <el-page-header @back="$router.go(-1)" content="账户交易记录" class="page-header" />

    <el-card class="account-card">
      <!-- 账户信息概览 -->
      <div class="account-info">
        <el-descriptions title="账户信息" border :column="isMobile ? 1 : 3">
          <el-descriptions-item label="账户ID">{{ accountData.accountId }}</el-descriptions-item>
          <el-descriptions-item label="账号">{{ accountNumber }}</el-descriptions-item>
          <el-descriptions-item label="账户类型">{{ accountType }}</el-descriptions-item>
          <el-descriptions-item label="当前余额" :span="isMobile ? 1 : 2">
            <span class="balance">¥{{ balance.toFixed(2) }}</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 交易记录表格 -->
      <h3 class="transaction-title">交易记录</h3>
      <div class="table-container">
        <el-table
            :data="processedTransactions"
            stripe
            border
            v-loading="loading"
            style="width: 100%"
            empty-text="暂无交易记录"
            :size="tableSize"
        >
          <el-table-column prop="id" label="交易ID" width="100" align="center" />
          <el-table-column label="交易类型" width="120" align="center">
            <template #default="{row}">
              <el-tag
                  :type="getTransactionTypeTag(row.type)"
                  :size="tagSize"
              >
                {{ formatTransactionType(row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="金额" width="150" align="right">
            <template #default="{row}">
              <span :class="getAmountClass(row.type)">
                {{ ['WITHDRAW', 'TRANSFER_OUT'].includes(row.type) ? '-' : '+' }}¥{{ row.amount.toFixed(2) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="转出账户" min-width="120" align="center">
            <template #default="{row}">
              <span v-if="row.fromAccount">{{ row.fromAccount }}</span>
              <span v-else class="empty-cell">--</span>
            </template>
          </el-table-column>
          <el-table-column label="转入账户" min-width="120" align="center">
            <template #default="{row}">
              <span v-if="row.toAccount">{{ row.toAccount }}</span>
              <span v-else class="empty-cell">--</span>
            </template>
          </el-table-column>
          <el-table-column label="交易时间" min-width="160" align="center">
            <template #default="{row}">
              <span class="time-text">{{ formatDateTime(row.createdAt) }}</span>
            </template>
          </el-table-column>
          <!-- 新增的交易详情列 -->
          <el-table-column label="交易详情" width="120" align="center" fixed="right">
            <template #default="{row}">
              <el-button
                  size="small"
                  @click="viewTransactionDetail(row.id)"
              >
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { accountApi } from '@/api'

export default {
  name: 'AccountTransactions',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const loading = ref(false)
    const windowWidth = ref(window.innerWidth)

    // 响应式布局计算
    const isMobile = computed(() => windowWidth.value < 768)
    const tableSize = computed(() => isMobile.value ? 'small' : 'medium')
    const tagSize = computed(() => isMobile.value ? 'small' : 'medium')

    // 账户数据
    const accountData = ref({
      accountId: Number(route.params.id) || 0,
      transactions: []
    })

    // 查看交易详情
    const viewTransactionDetail = (transactionId) => {
      router.push(`/transactions/${transactionId}`)
    }

    // 处理交易数据
    const processedTransactions = computed(() => {
      return accountData.value.transactions.map(trans => ({
        ...trans,
        fromAccount: trans.fromAccountId ? `账户${trans.fromAccountId}` : null,
        toAccount: trans.toAccountId ? `账户${trans.toAccountId}` : null,
        type: trans.type === 'TRANSFER'
            ? (trans.toAccountId === accountData.value.accountId ? 'TRANSFER_IN' : 'TRANSFER_OUT')
            : trans.type
      }))
    })

    // 计算余额
    const balance = computed(() => {
      return processedTransactions.value.reduce((total, trans) => {
        const amount = Number(trans.amount) || 0
        return ['DEPOSIT', 'TRANSFER_IN'].includes(trans.type)
            ? total + amount
            : total - amount
      }, 0)
    })

    // 账户信息
    const accountNumber = computed(() => {
      return `622588${String(accountData.value.accountId).padStart(4, '0')}`
    })

    const accountType = ref('储蓄账户')

    // 格式化交易类型
    const formatTransactionType = (type) => {
      const typeMap = {
        'DEPOSIT': '存款',
        'WITHDRAW': '取款',
        'TRANSFER_IN': '转账入账',
        'TRANSFER_OUT': '转账出账'
      }
      return typeMap[type] || type
    }

    // 交易类型标签样式
    const getTransactionTypeTag = (type) => {
      const typeTagMap = {
        'DEPOSIT': 'success',
        'WITHDRAW': 'danger',
        'TRANSFER_IN': 'primary',
        'TRANSFER_OUT': 'warning'
      }
      return typeTagMap[type] || ''
    }

    // 金额显示样式
    const getAmountClass = (type) => {
      return {
        'amount-positive': type === 'DEPOSIT' || type === 'TRANSFER_IN',
        'amount-negative': type === 'WITHDRAW' || type === 'TRANSFER_OUT'
      }
    }

    // 格式化日期时间
    const formatDateTime = (isoString) => {
      try {
        const date = new Date(isoString)
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false
        }).replace(/\//g, '-')
      } catch {
        return isoString || '--'
      }
    }

    // 获取交易记录
    const fetchTransactions = async () => {
      loading.value = true
      try {
        const response = await accountApi.getTransactions(route.params.id)

        if (response.state === 2000) {
          accountData.value = {
            accountId: response.data.accountId || Number(route.params.id),
            transactions: response.data.transactions || []
          }
        } else {
          throw new Error(response.message || '获取交易记录失败')
        }
      } catch (error) {
        ElMessage.error(`加载失败: ${error.message}`)
      } finally {
        loading.value = false
      }
    }

    // 响应式处理
    const handleResize = () => {
      windowWidth.value = window.innerWidth
    }

    onMounted(() => {
      fetchTransactions()
      window.addEventListener('resize', handleResize)
    })

    return {
      loading,
      accountData,
      accountNumber,
      accountType,
      balance,
      processedTransactions,
      isMobile,
      tableSize,
      tagSize,
      formatTransactionType,
      getTransactionTypeTag,
      getAmountClass,
      formatDateTime,
      viewTransactionDetail
    }
  }
}
</script>

<style scoped>
/* 原有样式保持不变 */
.account-transactions {
  padding: 16px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 20px;
}

.account-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.account-info {
  padding: 16px;
}

.transaction-title {
  margin: 24px 0 16px 16px;
  font-size: 18px;
  color: #333;
}

.table-container {
  padding: 0 16px 16px;
  overflow-x: auto;
}

.balance {
  font-weight: bold;
  color: #409EFF;
  font-size: 16px;
}

.amount-positive {
  color: #67C23A;
  font-weight: bold;
}

.amount-negative {
  color: #F56C6C;
  font-weight: bold;
}

.time-text {
  font-family: monospace;
}

.empty-cell {
  color: #999;
  font-style: italic;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .account-transactions {
    padding: 12px;
  }

  .account-info {
    padding: 12px;
  }

  .transaction-title {
    margin: 16px 0 12px 12px;
    font-size: 16px;
  }

  .table-container {
    padding: 0 12px 12px;
  }
}

@media (max-width: 480px) {
  .account-transactions {
    padding: 8px;
  }

  .account-info {
    padding: 8px;
  }

  .transaction-title {
    margin: 12px 0 8px 8px;
    font-size: 15px;
  }
}
</style>